'use client'
import React, { useEffect, useState } from "react";
import { 
  Button, 
  Card, 
  CardBody, 
  Spinner, 
  Textarea, 
  Avatar,
  Pagination,
  Divider,
  Tooltip,
  useDisclosure,
  Popover,
  PopoverTrigger,
  PopoverContent
} from "@nextui-org/react";
import { 
  createComment, 
  getNoteComments,
  deleteComment
} from "@/app/service/commentService";
import { FiMessageSquare, FiSend, FiMoreVertical, FiTrash2 } from "react-icons/fi";
import { AuthenticationChecker } from "@/app/config/authenticationChecker";
import { useRouter } from "next/navigation";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import 'dayjs/locale/zh-cn';
import AuthModal from "@/app/components/auth/authModal";

// 配置dayjs
dayjs.extend(relativeTime);
dayjs.locale('zh-cn');

interface CommentSectionProps {
  noteId: number;
  onCommentUpdate?: () => void;
}

export default function CommentSection({ noteId, onCommentUpdate }: CommentSectionProps) {
  const router = useRouter();
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [currentUser, setCurrentUser] = useState("");
  const [isLoading, setIsLoading] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [commentContent, setCommentContent] = useState("");
  const [comments, setComments] = useState<any[]>([]);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const pageSize = 10;

  // 登录弹窗状态
  const { isOpen, onOpen, onOpenChange } = useDisclosure();

  // 删除确认状态
  const [confirmDeleteId, setConfirmDeleteId] = useState<number | null>(null);
  const [isDeleting, setIsDeleting] = useState(false);

  // 检查用户登录状态
  useEffect(() => {
    const checkAuth = async () => {
      try {
        const [authenticated, username] = AuthenticationChecker();
        setIsAuthenticated(authenticated);
        if (authenticated && username) {
          setCurrentUser(username.toString());
        }
      } catch (error) {
        console.error("认证检查失败:", error);
      }
    };
    
    checkAuth();
  }, []);

  // 加载评论
  useEffect(() => {
    fetchComments();
  }, [noteId, page]);

  // 获取评论数据
  const fetchComments = async () => {
    if (!noteId) return;
    
    setIsLoading(true);
    try {
      const response = await getNoteComments(noteId, page, pageSize);
      if (response && response.code === 200 && response.data) {
        setComments(response.data.records || []);
        setTotal(response.data.total || 0);
        
        // 更新评论数后通知父组件
        if (onCommentUpdate) {
          onCommentUpdate();
        }
      } else {
        setComments([]);
        setTotal(0);
      }
    } catch (error) {
      console.error("获取评论失败:", error);
      setComments([]);
      setTotal(0);
    } finally {
      setIsLoading(false);
    }
  };

  // 提交评论
  const handleSubmitComment = async () => {
    if (!isAuthenticated) {
      // 打开登录弹窗而不是导航到首页
      onOpen();
      return;
    }

    if (!commentContent.trim()) {
      return;
    }

    setIsSubmitting(true);
    try {
      await createComment({
        noteId,
        content: commentContent.trim()
      });
      setCommentContent("");
      fetchComments(); // 重新加载评论
      
      // 通知父组件评论数已更新
      if (onCommentUpdate) {
        onCommentUpdate();
      }
    } catch (error) {
      console.error("评论提交失败:", error);
    } finally {
      setIsSubmitting(false);
    }
  };

  // 删除评论
  const handleDeleteComment = async (commentId: number) => {
    if (!isAuthenticated) return;
    
    setIsDeleting(true);
    try {
      await deleteComment(commentId);
      setConfirmDeleteId(null);
      fetchComments(); // 重新加载评论
      
      // 通知父组件评论数已更新
      if (onCommentUpdate) {
        onCommentUpdate();
      }
    } catch (error) {
      console.error("删除评论失败:", error);
    } finally {
      setIsDeleting(false);
    }
  };

  // 格式化日期
  const formatDate = (date: string) => {
    if (!date) return "";
    return dayjs(date).fromNow();
  };

  return (
    <Card className="shadow-sm">
      <CardBody className="gap-3">
        <div className="flex items-center mb-2">
          <FiMessageSquare className="text-primary mr-2" size={18} />
          <h2 className="text-lg font-semibold">评论</h2>
          {total > 0 && (
            <span className="ml-2 text-sm text-gray-500">({total})</span>
          )}
        </div>

        {/* 评论表单 */}
        <div className="mb-4">
          <Textarea
            placeholder={isAuthenticated ? "写下你的评论..." : "请先登录再评论"}
            value={commentContent}
            onChange={(e) => setCommentContent(e.target.value)}
            disabled={isSubmitting}
            minRows={2}
            maxRows={5}
            className="mb-2"
          />
          <div className="flex justify-end">
            <Button
              color="primary"
              isDisabled={!commentContent.trim() || isSubmitting}
              isLoading={isSubmitting}
              onPress={handleSubmitComment}
              endContent={<FiSend size={16} />}
              size="sm"
            >
              发表评论
            </Button>
          </div>
        </div>

        <Divider className="my-2" />

        {/* 评论列表 */}
        {isLoading ? (
          <div className="flex justify-center items-center py-8">
            <Spinner color="primary" size="sm" label="加载评论中..." />
          </div>
        ) : comments.length === 0 ? (
          <div className="text-center py-8 text-gray-500">
            暂无评论，来添加第一条评论吧！
          </div>
        ) : (
          <div className="space-y-4">
            {comments.map((comment) => (
              <div key={comment.id} className="flex gap-3">
                <Avatar
                  src={comment.userAvatar}
                  name={comment.userName?.charAt(0) || "U"}
                  size="sm"
                  className="flex-shrink-0"
                />
                <div className="flex-grow">
                  <div className="flex justify-between items-center mb-1">
                    <span className="font-medium text-sm">{comment.userName || "用户"}</span>
                    <div className="flex items-center gap-2">
                      <Tooltip content={dayjs(comment.createdAt).format("YYYY-MM-DD HH:mm:ss")}>
                        <span className="text-xs text-gray-500">{formatDate(comment.createdAt)}</span>
                      </Tooltip>
                      
                      {/* 删除按钮 - 仅对评论作者显示 */}
                      {isAuthenticated && comment.userName === currentUser && (
                        <Popover placement="left">
                          <PopoverTrigger>
                            <Button
                              isIconOnly
                              size="sm"
                              variant="light"
                              className="text-default-400 hover:text-danger"
                            >
                              <FiMoreVertical size={16} />
                            </Button>
                          </PopoverTrigger>
                          <PopoverContent>
                            {confirmDeleteId === comment.id ? (
                              <div className="px-1 py-2">
                                <p className="text-sm text-danger mb-2">确认删除此评论?</p>
                                <div className="flex justify-end gap-2">
                                  <Button
                                    size="sm"
                                    variant="flat"
                                    onClick={() => setConfirmDeleteId(null)}
                                  >
                                    取消
                                  </Button>
                                  <Button
                                    size="sm"
                                    color="danger"
                                    isLoading={isDeleting}
                                    onClick={() => handleDeleteComment(comment.id)}
                                  >
                                    删除
                                  </Button>
                                </div>
                              </div>
                            ) : (
                              <Button
                                className="w-full"
                                variant="light"
                                color="danger"
                                size="sm"
                                startContent={<FiTrash2 size={16} />}
                                onClick={() => setConfirmDeleteId(comment.id)}
                              >
                                删除评论
                              </Button>
                            )}
                          </PopoverContent>
                        </Popover>
                      )}
                    </div>
                  </div>
                  <p className="text-sm">{comment.content}</p>
                </div>
              </div>
            ))}
            
            {/* 分页 */}
            {total > pageSize && (
              <div className="flex justify-center mt-4">
                <Pagination
                  total={Math.ceil(total / pageSize)}
                  page={page}
                  onChange={setPage}
                  showControls
                  size="sm"
                />
              </div>
            )}
          </div>
        )}
      </CardBody>
      
      {/* 登录弹窗 */}
      <AuthModal isOpen={isOpen} onOpenChange={onOpenChange} />
    </Card>
  );
} 